<template>
    <section class="upload-group-box">
        <div class="file-content" v-if="showBtn">
            <form :id="upload_form" class="upload-file" method="post" enctype="multipart/form-data"
                v-if="btns.includes('file')">
                <button type="button" class="el-button el-button--primary el-button--small" @click="clickFileUpload">
                    <span>附件上传</span>
                </button>
                <input :id="excelUpload" class="el-upload__input" type="file" name="uploadFile" @change="excelBatchFun(this)" accept="multipart/form-data" ref="updateBatchFile" />
            </form>
            <div class="upload-wrap" v-if="btns.includes('image')">
                <el-upload 
                    :show-file-list="isShow" 
                    :action="urlType" 
                    :on-progress="uploadProcess"
                    :on-success="uploadPicSuccess" 
                    :on-error="uploadPicError" 
                    :before-upload="beforePicUpload" 
                    list-type="picture" 
                    :data="upLoadData" 
                    name="uploadFile">
                    <el-button size="small" type="primary">上传图片</el-button>
                </el-upload>
            </div>
        </div>
        <!--附件展示 -->
        <div class="file-wrap clearfix">
            <div class="process-wrap" v-show="percentage > 0">
                <el-progress :percentage="percentage"></el-progress>
            </div>
            <ul class="filelist" v-if='flagList'>
                <li class="el-upload-list__item is-success" v-for="(item,index) in filelist" :key="item.uid">
                    <a class="el-upload-list__item-name file-width" style="width: 80%;position:relative;"  :title="showView ? '双击预览' : ''" @dblclick="bigFile(item)">
                        <i class="el-icon-document"></i>
                        {{ item.fileName }}
                    </a>
                    <i class="el-icon-download" @click="downloadFile(item)" v-if="download"></i>
                    <i class="el-icon-close" @click="removeFile(item,index)" title="删除" v-if="removeable"></i>
                </li>
            </ul>
            <!--图片展示-->
            <ul class="piclist" v-if='flagList' v-viewer>
                <li class="file" v-for="(item,index) in piclist" :key="item.uid">
                    <img :src="baseURL.fileURL + item.htmlUrl" alt="图片">
                    <i class="el-icon-close" @click="removePic(item,index)" title="删除" v-if="removeable"></i>
                </li>
            </ul>
            <preview-file ref="view"></preview-file>
        </div>
    </section>
</template>
<script>
import $ from "jquery";
import previewFile from '@/components/preview';
import { deleteAtthById } from "@/service/core/dictionary";
import { mapState } from 'vuex';
import baseURL from '@/utils/baseURL'
export default {
    name: "upload",
    components: { previewFile },
    props: {
        btns: {
            type: Array,
            default() {
                return ['file', 'image']
            }
        },
        showBtn: { // 是否显示上传按钮
            type: Boolean,
            default: true
        },
        showView: { // 是否允许预览文件
            type: Boolean,
            default: true
        },
        removeable: { // 附件是否可删除
            type: Boolean,
            default: true
        },
        download: { // 是否可下载
            type: Boolean,
            default: false
        },
        flag: { // 附件标识   用于区别反显时  两个上传组件绑定到一个工单id的情况。
            type: String,
            default: ''
        },
        flagList:{   //用于是否显示列表信息
            type:Boolean,
            default:true,
        },
        busiId: {
            type: String,
            default: ""
        },
        filelist: { // 附件
            type: Array,
            default() {
                return [];
            }
        },
        piclist: {
            //图片
            type: Array,
            default() {
                return [];
            }
        },
        fileMax: { // 附件最大上传数量
            type: Number,
            default: 0,
        },
        picMax: { // 图片最大上传数量
            type: Number,
            default: 0,
        }
    },
    data() {
        return {
            upload_form: 'upload_form' + new Date().getTime(),
            excelUpload: 'excelUpload' + new Date().getTime(),
            uploadBatchlist: "",
            showImg: false,
            imgSrc: "",
            isShow: false,
            percentage: 0, // 上传进度
            baseURL: baseURL
        }
    },
    computed: {
        ...mapState({
            token: state => state.token.token,
        }),
        urlType() {
            return this.baseURL.url + '/api-sys/sys/atth/upload';
        },
        upLoadData() {
            return {
               token: this.token,
               busiType: "image" + this.flag,
               busiId: this.busiId
            }
        },
    },
    methods: {
        removeFile(uid) { // 移除
            this.$confirm('确认删除该文件？', {type: 'warning'}).then(() => {
                const params = { ids: uid.id };
                deleteAtthById(params).then(res => {
                    if (res.data.code == 1000)
                        var index = this.filelist.findIndex(
                            v => v.id == uid.id
                        );
                    this.filelist.splice(index, 1);
                    this.$notify({
                        title: "提醒",
                        message: "附件删除成功",
                        type: "success"
                    });
                    this.$emit('refreshFileList'); // 删除后刷新附件列表 （如果有的话）
                })
                .catch(err => {
                    this.$notify({
                        title: "提示",
                        type: 'error',
                        message: "附件删除失败！"
                    });
                });
            }).catch(() => {})
        }, 
        excelBatchFun(a) { // 表单提交
            if(this.fileMax > 0 && this.filelist.length >= this.fileMax) {
                this.$notify({
                    title: '提示',
                    type: 'error',
                    message: `最多支持上传${this.fileMax}个附件！`
                })
                return
            }
            let val = $("#" + this.excelUpload).val();
            let that = this;
            var options = {
                target: "", //更换内容
                url: baseURL.url + "/api-sys/sys/atth/upload",
                data: {
                    token: this.token,
                    busiId: `${this.busiId}`,
                    busiType: "attachment" + this.flag,
                    isConvert: true
                },
                beforeSubmit: function(fileList, obj, config) { // 上传前 附件大小验证。
                    let size = fileList[0].value.size;
                    if(size > 1024*1024*10) {
                        that.$notify({
                            title: '提示',
                            type: 'error',
                            message: '上传附件大小不能超过10M！'
                        })
                        return false
                    }
                },
                success: function(response) {
                    let res = JSON.parse(response)
                    if(res.code == 1000) {
                        that.$notify.info({
                            title: "提示",
                            message: "附件上传成功！"
                        });
                        that.filelist.push(res.data);
                        that.percentage = 0;
                        that.$emit("uploadExcel", that.filelist);
                    }else {
                        that.$notify.error({
                            title: "提示",
                            message: "附件上传失败！"
                        });
                        that.percentage = 0;
                    }
                },
                uploadProgress: function(event, position, total, percentComplete) {
                    that.percentage = percentComplete;
                },
                resetForm: true,
                error: function() {
                    that.$notify.error({
                        title: "提示",
                        message: "附件上传失败！"
                    });
                    that.percentage = 0;
                }
            };
            $("#" + this.upload_form).ajaxSubmit(options);
        },
        bigFile(item) { // 文件预览
            if(this.showView) {
                this.$refs.view.showPreview(item.id);
                this.$emit('preview'); // 触发事件 关闭外部弹窗
            }
        },
        clickImg(e) {
            this.showImg = true;
            this.imgSrc = e.target.currentSrc;
        },
        viewImg() {
            this.showImg = false;
        },
        beforePicUpload(file) {
            if(this.picMax > 0 && this.piclist.length >= this.picMax) {
                this.$notify({
                    title: '提示',
                    type: 'error',
                    message: `最多支持上传${this.picMax}张图片！`
                })
                return false
            }
            let size = 1024 * 1024 * 10;
            let type = file.type.split("/")[0];
            if (file.size > size) {
                this.$notify.error("上传图片大小不能超过10M！");
                return false;
            }
            if (type != "image") {
                this.$notify.error("只能上传图片格式文件！");
                return false;
            }
        },
        uploadProcess(event, file, fileList) {
            this.percentage = parseInt(event.percent);
        },
        uploadPicSuccess(response, file, fileList) {
            if(response.code == 1000) {
                this.piclist.push(response.data);
                console.log(response)
                console.log(file)
                console.log(fileList)
                this.$emit("uploadPic", this.piclist);
                this.$notify({
                    message: "上传图片成功！",
                    type: "success"
                });
                this.percentage = 0;
            }
        },
        uploadPicError() {
            this.$notify.error("上传图片失败！");
            this.percentage = 0;
        },
        removePic(item, index) {
            this.$confirm('确认删除该图片？', {type: 'warning'}).then(() => {
                const params = { ids: item.response ? item.response.id : item.id };
                deleteAtthById(params).then(res => {
                    if (res.data.code == 1000) {
                        this.piclist.splice(index, 1);
                        this.$notify({
                            title: "提醒",
                            message: "图片删除成功",
                            type: "success"
                        });
                        this.$emit('refreshFileList'); // 删除后刷新附件列表 （如果有的话）
                    }
                })
                .catch(err => {
                    this.$notify({
                        title: "提示",
                        type: "error",
                        message: "图片删除失败！"
                    });
                });
            }).catch(() => {})
        },
        clickFileUpload() {
            $('#' + this.excelUpload).click();
        },
        downloadFile(item) { // 下载文件
            if(item.id) {
                window.location.href = `/api/api-sys/sys/atth/download?id=${item.id}`
            }
        },
    }
};
</script>
<style lang="scss">
.upload-group-box{

    .file-content {
        margin-bottom: 5px;
        .upload-file {
            position: relative;
            display: inline-block;
            input {
                opacity: 0;
            }
        }

        .upload-wrap {
            display: inline-block;
            margin-left: 15px;
        }
    }

    .file-wrap {
        .el-upload-list__item{
            height: 35px;
            line-height: 35px;
            display: flex;
            align-items: center;

            .el-upload-list__item-name {
                flex: 1;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
            }

            > i {
                position: static;
                margin-right: 10px;
                cursor: pointer;
            }

        }
    }

    .piclist {
        width: 100%;

        .file {
            cursor: pointer;
            width: 55px;
            height: 55px;
            border: 1px solid #ddd;
            border-radius: 5px;
            float: left;
            margin: 5px 5px 0 0;
            position: relative;
            overflow: hidden;

            img {
                width: 100%;
                height: 100%;
            }

            &:hover {
                i.el-icon-close {
                    display: block;
                }
            }

            i.el-icon-close {
                width: 16px;
                height: 16px;
                line-height: 16px;
                text-align: center;
                display: none;
                cursor: pointer;
                position: absolute;
                top: 2px;
                right: 2px;
                background: rgb(248, 8, 8);
                color: #fff;
                border-radius: 50%;
                overflow: hidden;
            }
        }
    }

}
</style>

